package com.gandong8.derby.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.gandong8.derby.core.exception.LoginException;
import com.gandong8.derby.core.exception.LoginRedirectException;
import com.gandong8.derby.core.util.RequestUtil;
import com.gandong8.derby.core.constant.DOConstant;
import com.gandong8.derby.core.exception.CommonException;
import com.gandong8.derby.pojo.entry.manual.User;
import com.gandong8.derby.pojo.vo.request.UserReqVO;
import com.gandong8.derby.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements UserService{
    @Value("${spring.security.user.name}")
    private String username;
    @Value("${spring.security.user.password}")
    private String password;
    @Value("${spring.security.user.password.salt:fwfsfds}")
    private String pwdSalt;


    @Override
    public User getUser(String username) {
        if(!this.username.equals(username)){
            return null;
        }
        User user = new User();
        user.setId(1L);
        user.setUsername(username);
        user.setPassword(this.password);
        return user;
    }

    @Override
    public void checkUser() {
        User user = (User) RequestUtil.getSession(DOConstant.USER_SESSION);
        if(user == null) {
            throw new LoginException("please login first");
        }
    }

    @Override
    public void userLogin(UserReqVO userReqVO) {
        if (!CaptchaUtil.ver(userReqVO.getCaptcha(), RequestUtil.getRequest())) {
            CaptchaUtil.clear(RequestUtil.getRequest());
            throw new CommonException("验证码不正确");
        }
        CaptchaUtil.clear(RequestUtil.getRequest());
        User user = getUser(userReqVO.getUsername());
        if(user == null) {
            throw new CommonException("用户不存在");
        }
        if(!SecureUtil.sha1(userReqVO.getPassword()+pwdSalt).equals(user.getPassword())) {
            throw new CommonException("密码不正确");
        }
        user.setPassword(null);
        RequestUtil.setSession(DOConstant.USER_SESSION, user);
    }

    @Override
    public void userLoginOut() {
        RequestUtil.clearSession(DOConstant.USER_SESSION);
        RequestUtil.clearSession(DOConstant.SITE_SECRET);
        throw new LoginRedirectException("");
    }

    @Override
    public void userLogSave() {

    }
}
